#include "Thread.h"
#include <iostream>
void* Thread::static_run(void * arg)
{
	Thread * pt = (Thread*)arg;
  
	 pt->main();
	
	return NULL;
}

Thread::Thread(bool isDetachable)
{
detached=isDetachable; 
created=false;
joined=false;

}

void Thread::start()
{
	created=true;
	setRunning(true);
	int res=0;
	res=pthread_create(&(this->t),NULL,static_run,(void*)this);	
	if(res!=0)
	{
	 status=ERROR_THREAD;
	}
}

bool Thread::running()
{
	bool tmp;
	lock.Enter();
	tmp=isrunning;
	lock.Release();
	return tmp;
}

void Thread::join()
{
 if(running())
 {
  if(!joined)
   { 
   
     #ifdef DEP
     std::cout<<"-->Hizo un join"<<std::endl;
     #endif
     int res=0;
     
     res=pthread_join((this->t),NULL);
     
    
     	
     if(res==0)
     {
     joined=true;
     }
    }
    
   }
}
void Thread::setRunning(bool value)
{
lock.Enter();
isrunning=value;
lock.Release();
}

int Thread::getStatus()
{
	int tmp=0;
	lock.Enter();
	tmp=status;
	lock.Release();
	
	return tmp;

}

void Thread::setStatus(int estado)
{
	lock.Enter();
status=estado;
lock.Release();

}
void Thread::sleep(unsigned long msec)
{	

#ifdef WIN32
	Sleep(msec);
#else
	usleep(msec*1000);
#endif
}

void Thread::stop()
{
setRunning(false);

}
Thread::~Thread()
{
	if (created)
	{
	
	if(detached)
	{
	/*El hilo sigue corriendo, y cuando termina
	se liberan sus recursos*/
		pthread_detach(this->t);
	}
	else
	{
		Thread::join();
		
	}
		
	}
		
		
}
